package com.FH.permission.sys_menu;

import com.FH.organization.Attachment.AttachmentResource;
import com.FH.util.AccessDB;
import com.FH.util.FileProcess;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by acer on 2016/8/3.
 */
@Stateless
public class SysmenuDAOImpl extends AccessDB implements SysmenuDAO {
    @Inject
    AttachmentResource attachmentResource;

    @Override
    public ResultDTO getSysmenuInfo(String search, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from sys_menu where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
            }

            if (json.has("sys_menu_id")) {
                //sql_w += " AND sys_menu_id = "+json.getString("sys_menu_id");
                sql_w += " AND sys_menu_id ='" + json.getString("sys_menu_id") + "'";
            }
            if (json.has("parent_sys_menu_id")) {
                //sql_w += " AND parent_sys_menu_id = "+json.getString("parent_sys_menu_id");

                String parent_sys_menu_id = json.getString("parent_sys_menu_id");
                if (!parent_sys_menu_id.equals("")) {
                    sql_w += " AND parent_sys_menu_id ='" + json.getString("parent_sys_menu_id") + "'";
                } else {
                    sql_w += " AND (parent_sys_menu_id IS NULL OR parent_sys_menu_id='')";
                }

            } else {
                sql_w += " AND (parent_sys_menu_id IS NULL OR parent_sys_menu_id='')";
            }

            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);//查询此数据是否存在

            List<String[]> seresult = new ArrayList<String[]>();

            List<SysmenuShowDTO> result = new ArrayList<SysmenuShowDTO>();

            if (!existName.equals("0")) {
                String sql = "select sys_menu_id,sys_menu_name,sys_menu_url,sys_menu_create,sys_menu_create_time,sys_menu_modify," +
                        " sys_menu_modify_time,parent_sys_menu_id,menu_order,attachment_id from sys_menu where 1=1" + sql_w + " ORDER BY menu_order ASC " + sql_page;
                seresult = this.getReportingTo(sql);

                for (int i = 0; i < seresult.size(); i++) {

                    SysmenuShowDTO sysmenuShowDTO = new SysmenuShowDTO();
                    sysmenuShowDTO.setSys_menu_id(seresult.get(i)[1]);
                    sysmenuShowDTO.setSys_menu_name(seresult.get(i)[2]);
                    sysmenuShowDTO.setSys_menu_url(seresult.get(i)[3]);
                    sysmenuShowDTO.setSys_menu_create(seresult.get(i)[4]);
                    sysmenuShowDTO.setSys_menu_create_time(seresult.get(i)[5]);
                    sysmenuShowDTO.setSys_menu_modify(seresult.get(i)[6]);
                    sysmenuShowDTO.setSys_menu_modify_time(seresult.get(i)[7]);
                    sysmenuShowDTO.setParent_sys_menu_id(seresult.get(i)[8]);
                    sysmenuShowDTO.setMenu_order(seresult.get(i)[9]);
                    sysmenuShowDTO.setAttachment_id(seresult.get(i)[10]);
                    ResultDTO attach = null;
                    if (seresult.get(i)[10] != null && !seresult.get(i)[10].equals("")) {
                        attach = attachmentResource.getAttachmentInfo("{attachment_id:" + seresult.get(i)[10] + "}", "1", "1");
                        sysmenuShowDTO.setImages(attach.getValues());
                    }

                    if (json.has("parent_sys_menu_id")) {
                        //获取他的父id
                        List<String[]> menu = new ArrayList<String[]>();

                        List<SysmenuShowDTO> menuDTO = new ArrayList<SysmenuShowDTO>();
                        String sys_menu_id = seresult.get(i)[1];
                        String parent_sql = "select sys_menu_id,sys_menu_name,sys_menu_url,sys_menu_create,sys_menu_create_time,sys_menu_modify,sys_menu_modify_time " +
                                ",parent_sys_menu_id,menu_order,attachment_id from sys_menu where parent_sys_menu_id='" + sys_menu_id + "' ORDER BY sys_menu_create_time";
                        menu = this.getReportingTo(parent_sql);
                        for (int j = 0; j < menu.size(); j++) {

                            SysmenuShowDTO sysmenuShowDTO1 = new SysmenuShowDTO();
                            sysmenuShowDTO1.setSys_menu_id(menu.get(j)[1]);
                            sysmenuShowDTO1.setSys_menu_name(menu.get(j)[2]);
                            sysmenuShowDTO1.setSys_menu_url(menu.get(j)[3]);
                            sysmenuShowDTO1.setSys_menu_create(menu.get(j)[4]);
                            sysmenuShowDTO1.setSys_menu_create_time(menu.get(j)[5]);
                            sysmenuShowDTO1.setSys_menu_modify(menu.get(j)[6]);
                            sysmenuShowDTO1.setSys_menu_modify_time(menu.get(j)[7]);
                            sysmenuShowDTO1.setParent_sys_menu_id(menu.get(j)[8]);
                            sysmenuShowDTO1.setMenu_order(seresult.get(i)[9]);
                            sysmenuShowDTO1.setAttachment_id(seresult.get(i)[10]);
                            ResultDTO attach2 = null;
                            if (seresult.get(i)[10] != null && !seresult.get(i)[10].equals("")) {
                                attach2 = attachmentResource.getAttachmentInfo("{attachment_id:" + seresult.get(i)[10] + "}", "1", "1");
                                sysmenuShowDTO1.setImages(attach2.getValues());
                            }
                            menuDTO.add(sysmenuShowDTO1);


                        }
                        sysmenuShowDTO.setUser(menuDTO);

                    }
                    result.add(sysmenuShowDTO);
                }
            }

            if (seresult.size() != 0) {
                resultDTO.setValues(result);
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultDTO;
    }

    @Override
    public ResultDTO addSysmenuInfo(SysmenuPullDTO sysmenuPullDTO) {

        int resultls = 0;
        ResultDTO resultDTO = new ResultDTO();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");


        String sys_menu_name = sysmenuPullDTO.getSys_menu_name();
        String sql = "select * from sys_menu where sys_menu_name='" + sys_menu_name + "'";
        String sum = getReportingToOne(sql);
        if (!sum.equals("")) {

            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("菜单信息已存在，请重新分配");
            return resultDTO;
        }


        String attach_id = "";
        if (null != sysmenuPullDTO.getFilestream() && !"".equals(sysmenuPullDTO.getFilestream())) {
            attach_id = getImage(sysmenuPullDTO);
        }

        String Orgrole_insert = "";
        Orgrole_insert = "insert into sys_menu (sys_menu_id,sys_menu_name,sys_menu_url,sys_menu_create,sys_menu_create_time,sys_menu_modify,sys_menu_modify_time,parent_sys_menu_id,attachment_id)" +
                "values('" + uuid + "','" + sysmenuPullDTO.getSys_menu_name() + "','" + sysmenuPullDTO.getSys_menu_url() + "','" + sysmenuPullDTO.getSys_menu_create() + "'" +
                ",'" + df.format(new Date()) + "','" + sysmenuPullDTO.getSys_menu_modify() + "','" + df.format(new Date()) + "','" + sysmenuPullDTO.getParent_sys_menu_id() + "','" + attach_id + "')";

        resultls = addReportingTo(Orgrole_insert);
        if (resultls != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }

    @Override
    public ResultDTO updateSysmenuInfo(SysmenuPullDTO sysmenuPullDTO) {
        ResultDTO resultDTO = new ResultDTO();
        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //更新sql语句
        QUERY += "update sys_menu set sys_menu_modify_time = '" + time + "'";
        if (null != sysmenuPullDTO.getAttachment_id() && !"".equals(sysmenuPullDTO.getAttachment_id()) && null != sysmenuPullDTO.getFilestream() && !"".equals(sysmenuPullDTO.getFilestream())) {
            //调用修改文件方法
            updateImage(sysmenuPullDTO);
        } else if (null != sysmenuPullDTO.getFilestream() && !"".equals(sysmenuPullDTO.getFilestream())) {
            String uid = getImage(sysmenuPullDTO);
            QUERY += ",attachment_id='" + uid + "'";
        }
        QUERY += " where sys_menu_id = '" + sysmenuPullDTO.getSys_menu_id() + "'";

        int result = this.addReportingTo(QUERY);

        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }


    @Override
    public ResultDTO deleteSysmenuInfo(SysmenuShowDTO sysmenuPullDTO) {

        //删除之前查询一下该表是否有记录
        String sql = "select count(1) from sys_menu where sys_menu_id='" + sysmenuPullDTO.getSys_menu_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        if (!existName.equals(0)) {

            String QUERY = "";
            QUERY += "delete from sys_menu where sys_menu_id='" + sysmenuPullDTO.getSys_menu_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        ResultDTO resultDTO = new ResultDTO();
        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }


    public String getImage(SysmenuPullDTO sysmenuPullDTO) {
        ResultDTO resultDTO = new ResultDTO();
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/menu";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + uuid + ".png";


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(sysmenuPullDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/menu/" + uuid + ".png";

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //插入头像表
            enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time,file_type,file_name) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "','" + uuid + ".png" + "','" + uuid + ".png" + "')";
            // enpenform_image += "insert into file(file_id,file_addr,file_time,filegui_id,file_name) values ('" + uuid + "','" +imgurl+ "','" +df.format(new Date()) + "','" + dataDTO.getFilegui_id() + "','" + dataDTO.getFiletype() + "')";
        }

        //执行sql
        resultls = addReportingTo(enpenform_image);
        if (resultls != 0) {
            return uuid;
        }
        return null;
    }

    public String updateImage(SysmenuPullDTO sysmenuPullDTO) {
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/menu";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + uuid + ".png";

        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(sysmenuPullDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl =  "/menu/" + uuid + ".png";

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //修改头像表
            enpenform_image += "update attachment set attachment_addr='" + imgurl + "',head_portrait_time = '" + df.format(new Date()) + "',file_type = '" + uuid + ".png" + "',file_name = '" + uuid + ".png" + "' where attachment_id='" + sysmenuPullDTO.getAttachment_id() + "'";
            // enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "')";
        }

        //执行sql
        resultls = addReportingTo(enpenform_image);

        if (resultls != 0) {
            return uuid;
        }
        return null;
    }
}
